package com.school.sports.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 安全工具类
 * 提供获取当前用户信息的功能
 */
public class SecurityUtils {

    /**
     * 获取当前用户名
     * @return 用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            return ((UserDetails) authentication.getPrincipal()).getUsername();
        }
        return "system";
    }

    /**
     * 获取当前用户ID
     * 注意：这里需要根据实际情况实现，可能需要从数据库查询或从JWT token中解析
     * @return 用户ID
     */
    public static Long getCurrentUserId() {
        // 这里需要根据实际项目情况来实现
        // 可以从JWT token中解析，或者从当前登录用户对象中获取
        // 暂时返回1L作为默认值
        try {
            // 如果用户实体包含ID信息，可以这样获取：
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.getDetails() instanceof java.util.Map) {
                Object userId = ((java.util.Map) authentication.getDetails()).get("userId");
                if (userId instanceof Long) {
                    return (Long) userId;
                } else if (userId instanceof Integer) {
                    return ((Integer) userId).longValue();
                } else if (userId instanceof String) {
                    return Long.parseLong((String) userId);
                }
            }

            // 或者从用户名查询数据库获取用户ID
            // 这里简化处理，返回默认值
            return 1L;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前用户角色
     * @return 用户角色
     */
    public static String getCurrentUserRole() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !authentication.getAuthorities().isEmpty()) {
            return authentication.getAuthorities().iterator().next().getAuthority();
        }
        return "ROLE_ANONYMOUS";
    }

    /**
     * 获取当前认证对象
     * @return 认证对象
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 判断当前用户是否已认证
     * @return true-已认证，false-未认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated()
               && !"anonymousUser".equals(authentication.getPrincipal());
    }

    /**
     * 判断当前用户是否具有指定角色
     * @param role 角色
     * @return true-具有角色，false-不具有角色
     */
    public static boolean hasRole(String role) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getAuthorities() == null) {
            return false;
        }

        return authentication.getAuthorities().stream()
                .anyMatch(authority -> authority.getAuthority().equals(role));
    }

    /**
     * 判断当前用户是否具有任意指定角色
     * @param roles 角色数组
     * @return true-具有任意角色，false-不具有任何角色
     */
    public static boolean hasAnyRole(String... roles) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getAuthorities() == null || roles == null) {
            return false;
        }

        return authentication.getAuthorities().stream()
                .anyMatch(authority -> {
                    String authorityStr = authority.getAuthority();
                    for (String role : roles) {
                        if (authorityStr.equals(role)) {
                            return true;
                        }
                    }
                    return false;
                });
    }
}